package com.own.business.question.business.util;

import com.own.business.question.entity.po.PracticeHistory;
import com.own.business.question.entity.vo.PracticeVo;
import com.own.component.common.util.list.ListUtil;
import org.apache.commons.lang3.StringUtils;

import java.util.stream.Collectors;

/**
 * PracticeUtil
 *
 * @author 陈学礼 （你是一段成熟的代码，要学会自己改bug）
 * @version 4.0.0
 * @date 2021/5/19 14:39
 * @since 4.0.0
 */
public class PracticeUtil {

    /**
     * 隐藏答案
     *
     * @param practice 练习信息
     */
    public static void hiddenAnswer(PracticeVo practice) {
        practice.getQuestionList().parallelStream().forEach(QuestionUtil::clearAnswer);
    }

    /**
     * 打乱答案顺序
     *
     * @param practice 练习信息
     */
    public static void shuffle(PracticeVo practice) {
        practice.getQuestionList().parallelStream().forEach(QuestionUtil::shuffle);
    }

    /**
     * 还原答案信息
     *
     * @param history 练习的流水信息
     */
    public static void restoreAnswer(PracticeHistory history) {
        if (StringUtils.isEmpty(history.getKeySortOrder()) || StringUtils.isEmpty(history.getAnswer())) {
            return;
        }
        var keySortOrderList = ListUtil.Spilt.toInteger(history.getKeySortOrder());
        // 拆散排序
        var answer = ListUtil.Spilt.to(history.getAnswer(), ",")
                .stream()
                // 去重
                .distinct()
                // 计算出ASCII马列表
                .map(item -> (int) item.toCharArray()[0] - 65)
                // 计算出真实的位置
                .map(item -> keySortOrderList.size() - 1 >= item ? keySortOrderList.get(item) : -1)
                // 过滤无效的值
                .filter(item -> item >= 0)
                // 排序
                .sorted()
                // 计算出待计算ASCII信息
                .map(item -> (char) (item + 64))
                .map(Object::toString)
                .collect(Collectors.joining(","));
        history.setAnswer(answer);
    }

}
